/**
 * This module contains utility functions to process with array
 */

/**
 * Sort an array by merge sort algorithm
 * @param arr
 * @returns {*}
 */
exports.array_merge_sort = function(arr, fn) {
    if (!fn) {
        fn = function(a, b) {
            return (a <= b);
        };
    }

    if (arr.length < 2)
        return arr;

    var middle = parseInt(arr.length / 2);
    var left = arr.slice(0, middle);
    var right = arr.slice(middle, arr.length);

    return this.array_merge(this.array_merge_sort(left, fn), this.array_merge_sort(right, fn), fn);
};

/**
 * Merge two array by merge sort algorithm
 * @param left
 * @param right
 * @param fn
 * @returns {Array}
 */
exports.array_merge = function(left, right, fn) {
    if (!fn) {
        fn = function(a, b) {
            return (a <= b);
        };
    }

    var result = [];

    while (left.length && right.length) {
        if (fn(left[0], right[0])) {
            result.push(left.shift());
        }
        else {
            result.push(right.shift());
        }
    }

    while (left.length)
        result.push(left.shift());

    while (right.length)
        result.push(right.shift());

    return result;
};

/*
*   Copy Object
*   TODO: Implement for the sub-object
* */
exports.clone = function(object){
    var ret = new Object();
    for(var att in object){
        ret.att = object.att;
    }
    return ret;
}
